package edu.java.ishop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;
import javax.sql.DataSource;

import edu.java.ishop.dao.UserDao;
import edu.java.ishop.model.User;
@Named
public class UserDatabaseDao implements UserDao {

	@Inject
	private DataSource dataSource;
	
	public UserDatabaseDao() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void delete(long Id) {
		// TODO Auto-generated method stub

	}

	@Override
	public User getById(long Id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<User> getAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean save(User model) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void delete(User model) {
		// TODO Auto-generated method stub

	}

	@Override
	public User getByUsernamePassword(String username, String password) {
		User result = null;
		try(Connection conn = dataSource.getConnection();
				PreparedStatement pstmt = conn.prepareStatement("select * from \"user\"where username = ? and password =?");){
				pstmt.setString(1,username);
				pstmt.setString(2,password);
				ResultSet rs = pstmt.executeQuery();
				
				if(rs.next()){
					result = new User(rs.getLong(1));
				
					result.setUsername(rs.getString(2));
					result.setPassword(rs.getString(3));
					
					
				}
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
		
		return result;
	}

	@Override
	public User getByUsername(String username) {
		User result = null;
		try(Connection conn = dataSource.getConnection();
				PreparedStatement pstmt = conn.prepareStatement("select * from \"user\"where username = ?");){
				pstmt.setString(1,username);
				
				ResultSet rs = pstmt.executeQuery();
				
				if(rs.next()){
					result = new User(rs.getLong(1));
				
					result.setUsername(rs.getString(2));
					result.setPassword(rs.getString(3));
					
					
				}
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
		
		return result;
	}

}
